import fs from 'node:fs';
import path from 'node:path';
import { readMdFile } from './WindowService/readMdFile';
import { CitationInfoItem, ImageCitationInfo } from '@p/main-windowObject';
import { isImageByFilename } from '@e/methods/image';

/**
 * 获取图片引用关系
 */
export async function getImageCitationInfo(paths: string | string[]): Promise<ImageCitationInfo> {
	const pathList: string[] = [];
	if (typeof paths === 'string') {
		pathList.push(paths);
	} else {
		pathList.push(...paths);
	}

	const imageCitationInfo: ImageCitationInfo = {
		mdFileInfoList: [],
		dirInfo: [],
		mdInfo: [],
	};

	// 读取文件
	for (let i = 0; i < pathList.length; i++) {
		const value = await readMdFile(pathList[i]);

		imageCitationInfo.mdFileInfoList.push(value);
	}

	// 获取文档中引用的本地图片的引用信息
	imageCitationInfo.mdInfo = imageCitationInfo.mdFileInfoList.map((mdFileInfo, index1) => {
		const obj: ImageCitationInfo['mdInfo'][0] = {
			filename: mdFileInfo.fileName,
			filePath: mdFileInfo.filePath,
			size: mdFileInfo.size,
			dirInfo: [],
		};

		mdFileInfo.imageInfo.forEach((imageInfo, index2) => {
			if (imageInfo.type === 'absolute' || imageInfo.type === 'relative') {
				const filename = imageInfo.filename as string;
				const absolute = imageInfo.absolute as string;
				const dirPath = path.dirname(absolute);
				var citationInfoItem: CitationInfoItem;

				// 在 imageCitationInfo.dirInfo 中查找引用信息，若查到了则直接使用
				const g = imageCitationInfo.dirInfo.reduce((t, item) => {
					if (item.dirPath === dirPath) {
						const o = item.citationInfo.find((t) => t.filename === filename);
						if (o) {
							t = o;
						}
					}

					return t;
				}, undefined as undefined | CitationInfoItem);

				if (g) {
					citationInfoItem = g;
				} else {
					citationInfoItem = {
						filename,
						fullPath: absolute,
						size: 0,
						exists: fs.existsSync(absolute),
						isImage: isImageByFilename(filename),
						isMdReference: true,
						mdReferencePath: mdFileInfo.filePath,
						mdReferenceFilename: path.basename(mdFileInfo.filePath),
						mdInfoIndex: index1,
						imageInfoID: imageInfo.id,
						imageInfoIndex: [index1, index2],
					};

					if (citationInfoItem.exists) {
						citationInfoItem.size = fs.readFileSync(absolute).length;
					}

					if (citationInfoItem.isImage) {
						citationInfoItem.imageReferencePath = imageInfo.localReference;
					}

					// 若文件不存在，则不添加到 dirInfo
					if (citationInfoItem.exists) {
						const tindex = imageCitationInfo.dirInfo.findIndex((t) => t.dirPath === dirPath);

						if (tindex === -1) {
							imageCitationInfo.dirInfo.push({
								dirPath,
								citationInfo: [citationInfoItem],
							});
						} else {
							imageCitationInfo.dirInfo[tindex].citationInfo.push(citationInfoItem);
						}
					}
				}

				const sindex = obj.dirInfo.findIndex((t) => t.dirPath === dirPath);

				if (sindex === -1) {
					obj.dirInfo.push({
						dirPath,
						citationInfo: [citationInfoItem],
					});
				} else {
					obj.dirInfo[sindex].citationInfo.push(citationInfoItem);
				}
			}
		});

		return obj;
	});

	// 获取文档中引用的本地图片目录的其他文件的引用信息
	imageCitationInfo.dirInfo.forEach((item, index) => {
		fs.readdirSync(item.dirPath).forEach((file) => {
			// 若文件已存在则不添加
			if (!item.citationInfo.some((t) => t.filename === file)) {
				const absolute = path.join(item.dirPath, file);

				const citationInfoItem: CitationInfoItem = {
					filename: file,
					fullPath: absolute,
					size: fs.readFileSync(absolute).length,
					exists: true,
					isImage: isImageByFilename(file),
					isMdReference: false,
				};

				if (citationInfoItem.isImage) {
					citationInfoItem.imageReferencePath = encodeURI('file://' + absolute.replace(/\\/g, '/'));
				}

				imageCitationInfo.dirInfo[index].citationInfo.unshift(citationInfoItem);

				imageCitationInfo.mdInfo.forEach((q1, n1) => {
					q1.dirInfo.forEach((q2, n2) => {
						if (q2.dirPath === item.dirPath) {
							if (!q2.citationInfo.some((x) => x.filename === file)) {
								imageCitationInfo.mdInfo[n1].dirInfo[n2].citationInfo.unshift(citationInfoItem);
							}
						}
					});
				});
			}
		});
	});

	return imageCitationInfo;
}
